package com.android.john;


//DeadLock can use Handler to fix

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.os.Handler;

public class HandlerDemo extends Activity {

	final static String TAG = "HandlerDemo";
	
	private Handler handler = new Handler();// hanlder run in main thread
	Runnable r = new Runnable() {
		public void run() {
			Log.d(TAG, "ready to run thread");
			Log.d(TAG, "handler--->" + Thread.currentThread().getId());
			Log.d(TAG, "handlername--->" + Thread.currentThread().getName());
			try {
				Thread.sleep(10000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			Log.d(TAG, "thread run over");
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.syncMethod();

		setContentView(R.layout.activity_handler);
	}

	private void syncMethod() {
		Log.d(TAG, "syncMethod start!");
		synchronized (this) {
			Log.d(TAG, "handler ready to sync");
			((Handler) handler).post(r);
			Log.d(TAG, "thread id --->" + Thread.currentThread().getId());
			Log.d(TAG, "Activityname--->" + Thread.currentThread().getName());
			Log.d(TAG, "handler sync done");
		}
		Log.d(TAG, "syncMethod end!");
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.handler, menu);
		return true;
	}

}
